var express = require('express');
var Router = express.Router();
let fs = require('fs');
var { createPdfByPage } = require('../service/pdf.js')
var { OssClient } = require('../service/oss.js')
var { sendMail } = require('../service/mail.js')
var { md5 } = require('../../utils/md5.js')
var { uuid } = require('../../utils/index.js')

const salt = 'VTh5QmYwMGFoWTBTT'

Router.get('/pdfMail', function (req, res) {
  (async () => {
    await createPdfByPage('https://crm.mytijian.com', 'report.pdf')
    sendMail('txq@mytijian.com', 'nodejs机器人', "361134446@qq.com",
      '这是邮件标题',
      '这是正文。<h2> 我的主页：ww.</br>', [
      {   // stream as an attachment
        filename: 'text888.pdf',
        content: fs.createReadStream('./temp/report.pdf')
      }
    ])
  })();

  res.end('Router pdf\n');
});

Router.get('/pdfOss', function (req, res) {
  res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});

  let { reportId, hospitalId, host, debug } = req.query
  host = host || 'https://crm.mytijian.com'
  let sign = md5(JSON.stringify({reportId, hospitalId}) + salt)
  if (!reportId || !hospitalId) {
    res.end('请传入reportId及hospitalId')
  }
  let fileName = `${sign}.pdf`;
  ;(async () => {
    try {
      let buf = await createPdfByPage(`${host}/#/report/detail?reportId=${reportId}&hospitalId=${hospitalId}&sign=${sign}`, fileName)
      let path = `examreport/${hospitalId}/${fileName}`
      if (debug) return res.end(`${path}`);
      
      OssClient.putBuffer(path, buf).then(() => {
        fs.unlinkSync(`./temp/${fileName}`);
        res.end(`${path}`);
      }, () => {
        res.end(`上传失败`);
      })
    } catch (error) {
      res.end(JSON.stringify(error));
    }
  })();
});

Router.get('/sendMail', function (req, res) {
  sendMail('txq@mytijian.com', 'nodejs机器人', "361134446@qq.com",
    '这是邮件标题',
    '这是正文。<h2> 我的主页：</h2> 地址为：<a href= www.latelee.org" target="_blank">www.latelee.org</a></br>');

  res.end('Router sendMail\n');
});

exports.route1 = Router
